package com.own.component.log.operation.core;

import com.own.constant.ConstantCommon;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ExtraLogOperationSpringHook
 *
 * @author chenxueli
 * @date 2022-09-12 13:29:00
 */
@Slf4j
@Component
public class ExtraLogOperationSpringHook {

    private static final Map<String, List<ExtraLogOperationHook>> CUSTOM_LOG_OPERATION_HOOK_MAP = new HashMap<>(8);
    private static final List<ExtraLogOperationHook> CUSTOM_LOG_OPERATION_HOOK_LIST = new ArrayList<>(8);

    @Resource
    private List<ExtraLogOperationHook> extraLogOperationHookList;

    @PostConstruct
    private void init() {
        extraLogOperationHookList.forEach(service -> {
            var type = service.clientType();
            if (!ConstantCommon.NONE.equals(service.name())) {
                if (StringUtils.isBlank(type)) {
                    CUSTOM_LOG_OPERATION_HOOK_LIST.add(service);
                } else {
                    CUSTOM_LOG_OPERATION_HOOK_MAP.computeIfAbsent(type, k -> new ArrayList<>()).add(service);
                }
                log.debug("自定义日志操作接口===>【{}:{}】完成注册", type, service.name());
            }
        });
    }

    /**
     * 获取对应的日志操作接口
     *
     * @param client 客户端
     * @return 日志操作接口
     */
    public List<ExtraLogOperationHook> get(String client) {
        if (StringUtils.isBlank(client)) {
            return CUSTOM_LOG_OPERATION_HOOK_LIST;
        }
        return CUSTOM_LOG_OPERATION_HOOK_MAP.getOrDefault(client, new ArrayList<>());
    }

}
